package mfh.liveroam.client;

import java.util.ArrayList;
import java.util.Iterator;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Hidden;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.gwtext.client.core.EventObject;
import com.gwtext.client.data.Store;
import com.gwtext.client.util.Format;
import com.gwtext.client.widgets.grid.GridPanel;
import com.gwtext.client.widgets.grid.event.GridRowListener;

public class LiveRoamEntryPoint implements EntryPoint {

	@Override
	public void onModuleLoad() {
		// TODO Auto-generated method stub
		final VerticalPanel vpanel = new VerticalPanel();
		HorizontalPanel hpanel = new HorizontalPanel();

		final TextBox userId = new TextBox();
		userId.setName("userId");

		final TextBox utcOffset = new TextBox();
		utcOffset.setName("utcOffset");

		utcOffset.addKeyUpHandler(new KeyUpHandler() {
			@Override
			public void onKeyUp(KeyUpEvent event) {
				// check is Integer
				try {
					Integer.parseInt(utcOffset.getValue());
				} catch (Exception e) {
					utcOffset.setValue("");
				}

			}

		});

		HorizontalPanel hpanel2 = new HorizontalPanel();

		final Label albumLabel = new Label();

		final Hidden albumHidden = new Hidden("albumId");
		albumLabel.setText("Selected Album:");

		hpanel2.add(albumLabel);
		hpanel2.add(albumHidden);

		// final ListBox lb = new ListBox();
		// lb.setName("albumId");
		hpanel.add(userId);

		vpanel.add(hpanel);
		// vpanel.add(lb);

		final WidgetFactory widgetFactory = new WidgetFactory();
		final MyGridPanel grid = widgetFactory
				.getGridPanel(this.getEmptyData());
		grid.addGridRowListener(new GridRowListener() {
			public void onRowClick(GridPanel grid, int rowIndex, EventObject e) {
				MyGridPanel myGridPanel = (MyGridPanel) grid;
				albumHidden.setValue(myGridPanel.getAlbumId(rowIndex));
				albumLabel.setText("Selected Album:"
						+ myGridPanel.getAlbumName(rowIndex));

				utcOffset.setValue(myGridPanel.getHourOffset(rowIndex));

				System.out.println(Format.format(
						"GridRowListener.onRowClick::rowIndex({0})", rowIndex));
			}

			public void onRowDblClick(GridPanel grid, int rowIndex,
					EventObject e) {
				System.out.println(Format.format(
						"GridRowListener.onRowDblClick::rowIndex({0})",
						rowIndex));
			}

			public void onRowContextMenu(GridPanel grid, int rowIndex,
					EventObject e) {
				System.out
						.println(Format
								.format(
										"GridRowListener.onRowContextMenu::rowIndex({0}),                                           ({1}), y({2})",
										rowIndex, e.getPageX(), e.getPageY()));
			}
		});

		vpanel.add(grid);
		vpanel.add(hpanel2);

		RootPanel.get("picasaAlbum").add(hpanel);
		RootPanel.get("picasaTable").add(vpanel);

		HorizontalPanel hpanel3 = new HorizontalPanel();
		hpanel3.add(utcOffset);
		final Label utcOffsetDesc = new Label();
		utcOffsetDesc.setText("hrs. ");
		hpanel3.add(utcOffsetDesc);

		RootPanel.get("utcOffset").add(hpanel3);

		System.out.println(vpanel.getWidgetCount());

		final Label loading = new Label();

		// Create a handler for the sendButton and nameField
		class MyHandler implements ClickHandler {
			/**
			 * Fired when the user clicks on the sendButton.
			 */
			public void onClick(ClickEvent event) {
				String strUserId = userId.getText();
				ArrayList<PicasaBean> list = getAlbums(strUserId);
				loading.setText(" loading...");

				// lb.clear();

			}

			private ArrayList getAlbums(String userId) {
				final ArrayList re = new ArrayList();
				PicasaServiceAsync service = GWT.create(PicasaService.class);

				service.getAlbums(userId, new AsyncCallback<ArrayList>() {
					public void onFailure(Throwable caught) {
						// Show the RPC error message to the user

					}

					public void onSuccess(ArrayList result) {
						Object[][] table = new Object[result.size()][];
						int i = 0;
						for (Iterator iterator = result.iterator(); iterator
								.hasNext();) {
							PicasaBean object = (PicasaBean) iterator.next();
							// lb.addItem(object.getCaptrion(), object
							// .getAlbumId());

							String gpxButton = object.isHasGpx() ? "<A target='_blank' href='/showLiveRoam?albumId="
									+ object.getAlbumId()
									+ "' >Show on Map</A>"
									: "";

							// String deleteButton = object.isHasGpx() ?
							// "<input type=button value='Delete' onclick='window.open(\"/showLiveRoam?isDeleteGpx=Y&albumId="
							// + object.getAlbumId()
							// +
							// "\",\"\",\"top=0, left=0, toolbar=no, menubar=no \");'>"
							// : "";

							Object[] row = new Object[] { object.getCaptrion(),
									gpxButton, object.getAlbumId(),
									object.getHourOffSet() };
							table[i] = row;
							i++;
						}

						Store store = widgetFactory.getStore(table);
						grid.reconfigure(store, widgetFactory.getColumnModel());
						store.reload();
						loading.setText("");

						grid.setData(table);

						// GridPanel grid = widgetFactory.getGridPanel(table);
						//						
						//					
						// final int gridPanelIndex = 1;
						// vpanel.remove(gridPanelIndex);
						// System.out.println(vpanel.getWidgetCount());
						//
						// vpanel.add(grid);

					}
				});

				return re;
			}

		}

		Button button = new Button("Get Albums");

		MyHandler handler = new MyHandler();

		button.addClickHandler(handler);
		hpanel.add(button);
		hpanel.add(loading);

		System.out.println(vpanel.getWidgetCount());

	}

	private Object[][] getEmptyData() {
		return new Object[][] { null };
	}

}
